š Data Structures vs Algorithms
A Data Structure stores and organizes data (like a list or dictionary). An Algorithm is a step-by-step set of instructions to solve a specific problem.
1. What is the main difference between a Data Structure and an Algorithm?
Explanation: Data structures hold and organize data; algorithms are step-by-step calculation rules.
2. Which of the following is a Linear Data Structure?
Explanation: Arrays and Lists store elements in sequential order, making them linear.
3. Which of the following is a Non-Linear Data Structure?
Explanation: Trees organize data hierarchically rather than sequentially.
4. What is the built-in Python function to find the smallest number in a list?
Explanation: min(nums) finds and returns the smallest item in an iterable.
Answer: A Data Structure is a specialized format for organizing, processing, retrieving, and storing data efficiently in memory.
Answer: An algorithm is an unambiguous, step-by-step procedure designed to perform a computation or solve a specific problem.
Answer: Linear structures arrange elements sequentially (e.g. Arrays, Linked Lists, Stacks, Queues). Non-linear structures arrange data hierarchically or interconnectedly (e.g. Trees, Graphs).
Answer: DSA tests core problem-solving capability, algorithmic efficiency, optimization skills, and how developers handle scale.
š Understanding Big-O Notation
O(1) means constant time (no matter how big N is). O(N) means time grows directly with the number of items.
1. What is the time complexity of accessing an array element by its index nums[i]?
Explanation: Array index lookup is O(1) constant time because memory address is directly calculated.
2. What time complexity does a single loop iterating through all N elements have?
Explanation: A single loop that visits every element once runs in O(N) linear time.
3. What time complexity do two nested loops of size N each typically produce?
Explanation: Nested loops over N elements run N * N = O(N²) times.
4. Which Big-O complexity represents the fastest possible running time?
Explanation: O(1) constant time takes the same fixed number of operations regardless of input size.
Answer: Big-O notation describes the upper bound (worst-case scenario) of time or space complexity as input size N grows towards infinity.
Answer: O(1) is constant time. O(N) scales linearly with input size. O(N²) scales quadratically (like nested loops over N elements).
Answer: Space complexity measures the total amount of additional working memory an algorithm needs relative to the input size.
Answer: From slowest to fastest: O(N²) < O(N) < O(log N) < O(1).
š 1. Array Traversal & Slicing
Python lists provide contiguous memory storage with O(1) indexed lookup and fast slicing capabilities.
š 2. Essential Array Operations ā Search & Two-Pointer Reverse
Fundamental array algorithms: searching for elements in O(N) time and reversing an array in-place using two opposite pointers in O(N) time and O(1) space.
1. What is the time complexity of inserting an element at index 0 of a list?
Explanation: Inserting at index 0 requires shifting all N elements one position to the right: O(N).
2. Which slice expression reverses a list in Python?
Explanation: [::-1] steps backwards through the list, reversing it.
3. What is the time complexity of finding the maximum value in an unsorted list of N numbers?
Explanation: In an unsorted list, every element must be inspected once: O(N).
4. What does nums.pop() without arguments do?
Explanation: pop() removes the last element in O(1) constant time.
Answer: Python lists are implemented as dynamic arrays of pointers to objects, automatically reallocating larger contiguous memory blocks when capacity is exceeded.
Answer: Appending at the end is amortized O(1), while inserting at index 0 is O(N) because all existing elements must shift right.
Answer: Using two pointers: swap the element at the left pointer with the element at the right pointer, then move pointers inward.
Answer: Kadane algorithm finds the maximum subarray sum in O(N) linear time.
š 1. Checking Palindromes (Slicing)
Strings are immutable sequences of characters in Python. Checking palindromes can be done concisely via slicing.
š 2. Two-Pointer Palindrome & Valid Anagram Check
Solve key interview string questions: verifying palindromes using O(1) auxiliary memory and checking if two strings are valid anagrams using frequency counting.
1. What is a palindrome?
Explanation: Palindromes like "racecar" or "radar" read the same in reverse.
2. What is the most efficient way to build a string from a list of words in Python?
Explanation: "".join() allocates memory once and executes in O(N) time.
3. What does "silent" and "listen" sharing the same character counts make them?
Explanation: Two words formed by rearranging the same letters are anagrams.
4. What does "abcde"[1:4] return?
Explanation: Index 1 is "b", and slice stops before index 4 ("e"), giving "bcd".
Answer: Check if sorted(s1) == sorted(s2) in O(N log N), or use collections.Counter(s1) == Counter(s2) in O(N) time.
Answer: Because strings are immutable, each += creates a new string object copying all characters, resulting in O(N²) time. Use "".join(list) in O(N) instead.
Answer: Convert the string to a set: set(s).
Answer: A substring is contiguous characters. A subsequence maintains relative order but does not need to be contiguous.
O(1) insertions and deletions at the head without memory shifting. Master all essential operations: First Add, Middle Add, Last Add and First Remove, Middle Remove, Last Remove for both Singly and Doubly Linked Lists.
š 1. Singly Linked List (SLL) ā Architecture & Traversal
In a Singly Linked List, every node encapsulates a data element and a single next pointer referencing the following node. The final node points to None indicating the end of the chain.
Head āāāŗ [ Data: 10 | next: ⢠] āāāŗ [ Data: 20 | next: ⢠] āāāŗ [ Data: 30 | next: None ]
š 2. SLL Insertions ā First Add, Middle Add & Last Add
Learn how to insert new elements into any position of a Singly Linked List:
- First Add (Prepend / Insert at Head):
O(1)time. Create new node, pointnew_node.next = self.head, then setself.head = new_node. - Middle Add (Insert at 0-based Index):
O(N)time. Traverse to indexindex - 1, configurenew_node.next = curr.next, and updatecurr.next = new_node. - Last Add (Append / Insert at Tail):
O(N)time (orO(1)with tail pointer). Traverse untilcurr.next is None, then assigncurr.next = new_node.
š 3. SLL Deletions ā First Remove, Middle Remove & Last Remove
Explore how nodes are deleted from any position in a Singly Linked List:
- First Remove (Delete Head):
O(1)time. Pointself.head = self.head.next. Python garbage-collects the unreferenced previous head. - Middle Remove (Delete by Index):
O(N)time. Traverse to the node immediately before the target:curr.next = curr.next.nextbypasses and drops the target node. - Last Remove (Delete Tail):
O(N)time. Traverse to the second-to-last node wherecurr.next.next is None, then assigncurr.next = None.
š 4. Doubly Linked List (DLL) ā Architecture & Bidirectional Traversal
A Doubly Linked List provides two pointer references per node: next (to the next node) and prev (to the predecessor node). This architecture enables forward and backward traversal in O(1) space overhead.
None <āā [ prev | Data: 10 | next ] āāāāŗ [ prev | Data: 20 | next ] āāāāŗ [ prev | Data: 30 | next ] āāāŗ None
š 5. DLL Insertions ā First Add, Middle Add & Last Add
Insert elements smoothly into a Doubly Linked List while maintaining bidirectional references:
- First Add:
O(1)time. Configurenew_node.next = self.headandself.head.prev = new_node, then reassignself.head = new_node. - Middle Add:
O(N)time. Re-link 4 pointers:new_node.next = curr.next,new_node.prev = curr,curr.next.prev = new_node, andcurr.next = new_node. - Last Add:
O(N)time (orO(1)with tail pointer). Locate tail node, settail.next = new_nodeandnew_node.prev = tail.
š 6. DLL Deletions ā First Remove, Middle Remove & Last Remove
Safely unlink nodes from a Doubly Linked List in all three fundamental scenarios:
- First Remove:
O(1)time. Advanceself.head = self.head.nextand setself.head.prev = None. - Middle Remove:
O(N)time. Bridge around target:curr.prev.next = curr.nextandcurr.next.prev = curr.prev. - Last Remove:
O(N)time (orO(1)with tail). Traverse to tail node, and disconnect it:curr.prev.next = None.
š 7. Circular Linked List (CLL) ā Node Architecture & Traversal
In a Circular Linked List, the last node's next pointer does not point to None. Instead, it wraps right back to the head node, creating a continuous closed loop. This structure is ideal for round-robin CPU schedulers, turn-based games, and media playlists.
Head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
š 8. CLL Insertions ā First Add, Middle Add & Last Add
Insert elements into a Circular Linked List at any position:
⢠Add First (Head): Create new node, traverse to the last node to point its next to the new node, and set self.head = new_node.
⢠Add Middle (Position): Traverse to position pos - 1 and insert between nodes: new_node.next = curr.next; curr.next = new_node.
⢠Add Last (Tail): Traverse to the last node, point it to new_node, and point new_node.next = self.head.
š 9. CLL Deletions ā First Remove, Middle Remove & Last Remove
Remove elements safely while maintaining the circular pointer structure:
⢠Remove First (Head): Find the last node, point its next to self.head.next, and advance head to self.head.next.
⢠Remove Middle (By Value): Traverse until curr.next.data == key, then bypass the target: curr.next = curr.next.next.
⢠Remove Last (Tail): Traverse until curr.next.next == self.head, then reconnect curr.next = self.head.
1. What is the time complexity of First Add (inserting at the head) in both SLL and DLL?
Explanation: First Add simply reassigns the head pointer and connects the new node to the existing head without traversing any other elements, running strictly in O(1) time.
2. In a Singly Linked List without a tail reference, why does Last Remove take O(N) time?
Explanation: Because there are no backward pointers, deleting the tail requires traversing from head to the second-to-last node so its next pointer can be safely set to None.
3. When deleting a node from the middle of a Doubly Linked List, how many pointer references must be updated?
Explanation: To cleanly bypass the middle node, the previous node's next must point to curr.next, and the next node's prev must point to curr.prev (2 pointer updates).
4. What is the fundamental memory difference between Singly and Doubly Linked List nodes?
Explanation: Each Doubly Linked List node maintains both prev and next reference addresses, allowing bidirectional traversal at the cost of additional pointer memory.
Answer: Arrays use contiguous memory blocks, granting instantaneous O(1) random index access (arr[i]), but insert/delete operations require O(N) element shifting. Linked Lists allocate memory dynamically node-by-node anywhere on the heap; adding or removing at the head or known pointer takes O(1) time without shifting, but finding the k-th element requires O(k) sequential traversal.
Answer: Using Floyd's Cycle Detection Algorithm (Tortoise & Hare): maintain a slow pointer moving 1 step and a fast pointer moving 2 steps. If fast and slow ever meet, a loop exists. To find the cycle's starting node, reset slow to head while leaving fast at the meeting point; advance both 1 step at a time until they collide at the loop entrance.
Answer: Use three pointers: prev = None, curr = head, and next_node = None. In a loop while curr is not None: save next_node = curr.next, reverse link curr.next = prev, slide prev = curr, and advance curr = next_node. Finally, update head = prev.
Answer: Key Edge Cases:
1. Empty List: Inserting or deleting when head is None.
2. Index 0: Modifying the head node must invoke add_first() or remove_first() to update the head reference.
3. Index Out of Bounds: Index greater than list length must either append to end or safely return without raising null pointer exceptions.
4. Single-Node List: Removing the only remaining node requires resetting head = None and tail = None.
š Valid Parentheses Problem (Top Tech Interview)
Given a string with brackets ()[]{}, verify if every opening bracket has an appropriate closing bracket in the exact reverse order using a LIFO Stack.
š Push & Pop in Stacks
Think of a stack of plates. You add to the top and take from the top. All operations take O(1) time.
1. What principle does a Stack follow?
Explanation: Stacks strictly follow Last-In, First-Out (LIFO).
2. Which method removes and returns the top item from a stack in Python?
Explanation: pop() removes the top (last) element.
3. What error occurs when popping an empty stack?
Explanation: Calling pop() on an empty list raises an IndexError.
4. Which problem is classically solved using a Stack?
Explanation: Valid parentheses matching is the textbook stack problem.
Answer: LIFO stands for Last-In, First-Out.
Answer: Undo/Redo features, browser history back button, function call stacks in recursion, and syntax matching (parentheses checking).
Answer: Push opening brackets onto the stack. When a closing bracket is found, check if it matches the popped top element. If stack is empty at the end, it is balanced.
Answer: Both push and pop are O(1) constant time operations.
š 1. FIFO Queue with collections.deque
A Queue follows First-In, First-Out (FIFO). In Python, collections.deque gives O(1) append and popleft.
š 2. Complete Queue ADT Class (Enqueue, Dequeue, Peek)
Production-ready object-oriented Queue class encapsulating enqueue(), dequeue(), peek(), is_empty(), and size().
1. What principle does a standard Queue follow?
Explanation: Queues process elements in First-In, First-Out order.
2. Which class in Python standard library provides O(1) queue operations?
Explanation: collections.deque provides O(1) appends and pops from both ends.
3. Which method removes the front element from a deque in O(1)?
Explanation: popleft() removes from the front of the deque.
4. Which graph traversal algorithm relies on a Queue?
Explanation: BFS traverses level by level using a queue.
Answer: FIFO stands for First-In, First-Out.
Answer: In a list, list.pop(0) is O(N) because all remaining elements must shift left. In collections.deque, popleft() is O(1) constant time.
Answer: CPU task scheduling, print queues, Breadth-First Search (BFS) in graphs, and message queues (RabbitMQ/Kafka).
Answer: A circular queue connects the last position back to the first position, reusing deallocated space efficiently.
š 1. Hash Maps & Sets in Python
Hash tables (dictionaries and sets) provide average O(1) time complexity for insertion, lookup, and deletion by hashing keys.
š 2. LeetCode #1 Two Sum (Optimal O(N) Hash Map)
Find two indices in an array that add up to a target sum. A brute-force nested loop runs in O(N²), but a Hash Map solves it in a single pass in O(N) time.
1. What is the average time complexity of searching a key in a hash map?
Explanation: Hash lookups run in O(1) constant time on average.
2. What happens when two different keys generate the same hash value?
Explanation: This event is called a Hash Collision.
3. What data structure does Python use internally for dictionaries and sets?
Explanation: Python dicts and sets are implemented using hash tables.
4. What is the time complexity of solving Two Sum using a hash map?
Explanation: One pass through the array with O(1) hash lookups gives O(N) time.
Answer: A hash function converts an input key into an integer index. A good hash function is deterministic, fast, and distributes keys uniformly to minimize collisions.
Answer: When two distinct keys produce the same hash index. Resolved via Chaining (linked lists in buckets) or Open Addressing (probing).
Answer: As you iterate through the array, check if target - current_num exists in a dictionary. If yes, you found the pair in O(1) lookup.
Answer: O(N) if all keys collide into the same bucket, though average is O(1).
š Base Case & Recursive Step
Without a base case, the function calls itself forever, causing a RecursionError (Stack Overflow).
1. What condition is mandatory in every recursive function to prevent it from calling itself forever?
Explanation: The Base Case stops recursion and begins returning results.
2. What error occurs when recursion calls itself without stopping in Python?
Explanation: Python raises RecursionError when recursion exceeds limits.
3. What data structure does the computer use internally to track recursive calls?
Explanation: The Call Stack manages function call frames in LIFO order.
4. What does fact(3) return if fact(n) = n * fact(n-1) with fact(1) = 1?
Explanation: 3 * 2 * 1 = 6.
Answer: Recursion is when a function calls itself. Its two essential components are: 1) Base Case (terminates recursion), and 2) Recursive Case (breaks problem into smaller subproblems).
Answer: The call stack is the memory stack where function frames (local variables, return addresses) are stored until the function returns.
Answer: Missing or unreachable base case, or recursion depth exceeding the call stack capacity.
Answer: When the recursive call is the final operation in the function, allowing compiler optimization.
š Binary Search on Sorted Data
Binary search requires sorted data. Compare middle element with target to eliminate half the array each step.
1. What condition MUST be true to perform Binary Search on an array?
Explanation: Binary search requires sorted elements to divide search space.
2. What is the time complexity of Binary Search on N elements?
Explanation: Halving the search space each step produces O(log N) complexity.
3. In an array of 1,000,000 sorted items, approximately how many comparisons does Binary Search take?
Explanation: log2(1,000,000) is approximately 20 comparisons.
4. What is the time complexity of Linear Search in worst case?
Explanation: Linear search inspects every element once: O(N).
Answer: The array or collection MUST be sorted in ascending or descending order.
Answer: Best case is O(1), and average/worst case is O(log N).
Answer: To prevent integer overflow in languages with fixed integer sizes like C/Java.
Answer: O(N) linear time in worst case, but it works on unsorted data.
š 1. Bubble Sort Logic & Early Exit
Bubble Sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. An optimized flag allows early exit in O(N) if the list is already sorted.
š 2. Selection Sort ā Finding Minimum & Swapping
Selection Sort divides the list into a sorted part and an unsorted part. In each pass, it finds the smallest element from the unsorted section and swaps it to the end of the sorted section. Runs in O(N²) comparisons with minimal swaps (O(N) swaps).
š 3. Insertion Sort ā Card Playing Insertion
Insertion Sort works the way people sort cards in hand: it picks the next element and shifts all larger sorted elements to the right to insert the key into its correct position. Highly efficient for small or nearly sorted arrays (Best Case O(N)).
š 4. Divide & Conquer Fast Sorts Preview & Complexity Table
While Bubble, Selection, and Insertion Sort run in O(N²) time, advanced Divide and Conquer algorithms like Merge Sort and Quick Sort run in blistering O(N log N) time! Explore full implementations in Topic 18.
⢠Bubble Sort : Best O(N) | Avg O(N²) | Worst O(N²) | Space O(1)
⢠Selection Sort : Best O(N²) | Avg O(N²) | Worst O(N²) | Space O(1)
⢠Insertion Sort : Best O(N) | Avg O(N²) | Worst O(N²) | Space O(1)
⢠Merge Sort : Best O(N log N) | Avg O(N log N) | Worst O(N log N) | Space O(N)
⢠Quick Sort : Best O(N log N) | Avg O(N log N) | Worst O(N²) | Space O(log N)
1. What is the average time complexity of Bubble Sort?
Explanation: Bubble sort uses nested loops, resulting in O(N²) time.
2. Which basic sort performs best on an already-sorted array in O(N) time?
Explanation: Insertion sort checks already-sorted elements in linear O(N) time.
3. What algorithm does Python built-in .sort() method use?
Explanation: Python uses Timsort, invented by Tim Peters.
4. Does Selection Sort always take O(N²) comparisons even if the list is already sorted?
Explanation: Selection sort scans the remainder of the array unconditionally: O(N²).
Answer: All three have a worst and average-case time complexity of O(N²).
Answer: A sort is stable if it preserves the relative order of duplicate elements with equal keys.
Answer: Insertion Sort runs in O(N) linear time on already or nearly sorted arrays.
Answer: Python uses Timsort (a hybrid of Merge Sort and Insertion Sort), which runs in O(N log N) worst-case and O(N) best-case.
š Two Sum on Sorted Array
With a sorted array, start left at 0 and right at end. If sum is too small, increment left. If too big, decrement right.
1. Why is the Two Pointers technique popular in coding interviews?
Explanation: Two pointers allows linear single-pass scanning without extra memory.
2. In Two Sum on a sorted array, what do you do if current sum < target?
Explanation: Increasing the left pointer accesses a larger number, increasing the sum.
3. What is the space complexity of the standard Two Pointers technique?
Explanation: Only two integer index variables are tracked: O(1).
4. Which famous problem is solved efficiently using Two Pointers?
Explanation: Container With Most Water is solved in O(N) time with two pointers.
Answer: A pattern where two indices traverse a data structure (often in opposite directions or at different speeds) to reduce O(N²) comparisons to O(N).
Answer: The input array or string is typically sorted or monotonic.
Answer: Left pointer at start, right pointer at end; swap characters and move pointers inward until they meet.
Answer: Two pointers can move independently in any direction. A sliding window maintains a contiguous sub-range (window) expanding or contracting.
š Fixed-Size Window Sum
To find max sum of k items, calculate first window sum. Then slide right: add incoming element and subtract outgoing element in O(1).
1. What time complexity does sliding window achieve for finding max sum of subarray of size K?
Explanation: Instead of summing K items each time, sliding window updates in O(1), giving O(N) total.
2. When sliding a fixed window one step to the right, what do you do to the running sum?
Explanation: Add new right element and subtract old left element.
3. Which problem is classically solved using a Dynamic Sliding Window?
Explanation: Longest substring without duplicates dynamically contracts when a duplicate is found.
4. What data structure is often paired with sliding window for unique character tracking?
Explanation: Hash sets check character presence in O(1) time.
Answer: A pattern to find optimal subarrays or substrings (e.g. max sum of size K, longest substring without repeating characters) in O(N) time instead of O(N*K).
Answer: Fixed-size window maintains a constant length K. Dynamic window expands with right pointer and shrinks with left pointer based on a condition.
Answer: new_sum = old_sum + new_element - outgoing_element in O(1) time.
Answer: O(N) time using two pointers and a hash set/map.
š BST Properties & Traversal
Inorder traversal (Left, Root, Right) of a Binary Search Tree always visits elements in sorted ascending order.
1. What rule defines a Binary Search Tree (BST)?
Explanation: BST ordering guarantees left < parent < right.
2. Which tree traversal visits a BST in sorted ascending order?
Explanation: Inorder traversal of a BST always yields sorted order.
3. What is the average time complexity of searching in a balanced BST?
Explanation: Halving search depth at each level gives O(log N).
4. What is the maximum number of children a node in a binary tree can have?
Explanation: A binary tree node has at most 2 children (left and right).
Answer: A binary tree where for every node, all values in its left subtree are strictly less than the node value, and all values in its right subtree are strictly greater.
Answer: Balanced BST is O(log N). In worst-case degenerate (skewed) tree, it degrades to O(N).
Answer: Inorder (Left-Root-Right), Preorder (Root-Left-Right), and Postorder (Left-Right-Root).
Answer: Inorder traversal always yields nodes in ascending sorted order.
š Min-Heap with heapq
heapq.heappush() adds an element in O(log N), and heapq.heappop() removes the smallest element in O(log N).
1. What element is always at index 0 (the root) of a Min-Heap?
Explanation: In a Min-Heap, the root node is always the smallest element.
2. Which Python module provides built-in heap functionality?
Explanation: heapq is the standard library heap module.
3. What is the time complexity of heappush() and heappop() in a heap of N items?
Explanation: Sifting up or down takes time proportional to tree height: O(log N).
4. What problem is commonly solved efficiently using a Heap?
Explanation: Kth largest/smallest element problems are solved in O(N log K) using heaps.
Answer: A heap is a specialized complete binary tree satisfying the heap property: Min-Heap (root is minimum) or Max-Heap (root is maximum).
Answer: heapq implements a Min-Heap by default.
Answer: Multiply values by -1 before pushing, and invert again when popping.
Answer: heapq.heapify() runs in O(N) linear time.
š BFS vs DFS Traversal
Represent graphs with adjacency lists (dictionaries). Use a visited set to avoid infinite loops in cycles.
1. What data structure is used to implement Breadth-First Search (BFS)?
Explanation: BFS visits nodes level by level using a FIFO Queue.
2. Which algorithm finds the shortest path in an unweighted graph?
Explanation: BFS explores layer by layer, naturally reaching targets in fewest steps.
3. What is the time complexity of BFS/DFS on a graph with V vertices and E edges?
Explanation: Every vertex and edge is examined at most once: O(V + E).
4. Why is a visited set essential when traversing graphs with cycles?
Explanation: Cycles will cause endless revisits without a visited set.
Answer: BFS (Breadth-First Search) explores neighbors level-by-level using a Queue. DFS (Depth-First Search) explores as deep as possible along each branch using Recursion or a Stack.
Answer: BFS guarantees finding the shortest path (minimum number of edges) in an unweighted graph.
Answer: Track visited nodes in a hash set: visited.add(node).
Answer: O(V + E) where V is vertices and E is edges.
š Coin Change with Greedy Choice
For canonical coin systems, always picking the largest coin possible minimizes total coins.
1. What decision strategy does a Greedy Algorithm make at each step?
Explanation: Greedy always picks the best option available right now.
2. Which of the following is solved optimally by a greedy approach?
Explanation: Fractional knapsack sorts by value/weight and takes greedily.
3. Does a greedy algorithm reconsider earlier decisions or backtrack?
Explanation: Greedy makes irrevocable local choices without backtracking.
4. What famous Minimum Spanning Tree algorithm is greedy?
Explanation: Kruskal and Prim algorithms greedily select smallest valid edges.
Answer: An algorithmic paradigm that makes the locally optimal choice at each stage with the hope of finding a global optimum.
Answer: No. Greedy works only for problems exhibiting the Greedy Choice Property and Optimal Substructure (e.g. Fractional Knapsack, Dijkstra, Huffman Coding).
Answer: Greedy makes one best local choice and never reconsiders. Dynamic Programming evaluates all subproblem choices and memoizes optimal solutions.
Answer: Dijkstra algorithm (shortest path) and Kruskal/Prim algorithms (Minimum Spanning Tree).
š 1. Merge Sort ā Divide, Conquer & Combine
Merge Sort recursively splits the array into two equal halves until single elements remain (Divide), sorts each half, and then merges the sorted halves using two pointers (Conquer & Combine). Guaranteed O(N log N) runtime in all cases and highly stable.
[ 38, 27, 43, 3, 9, 82, 10 ]
Divide āāāŗ [ 38, 27, 43 ] and [ 3, 9, 82, 10 ]
Conquer āāāŗ [ 27, 38, 43 ] and [ 3, 9, 10, 82 ]
Merge āāāŗ [ 3, 9, 10, 27, 38, 43, 82 ]
š 2. Quick Sort ā Pivot Selection & Partitioning
Quick Sort picks an element as a pivot and partitions the array into three subarrays: elements smaller than the pivot, elements equal to the pivot, and elements greater than the pivot. It recursively sorts the sub-partitions with average time complexity O(N log N).
Array: [ 10, 80, 30, 90, 40, 50, 70 ] | Pivot = 40
Left (< 40) : [ 10, 30 ]
Middle (== 40) : [ 40 ]
Right (> 40) : [ 80, 90, 50, 70 ]
š 3. Merge Sort vs. Quick Sort ā Head-to-Head Comparison
Understand when to choose Merge Sort vs Quick Sort in real-world interviews and system designs:
⢠Memory Usage: Merge Sort requires O(N) auxiliary space for temporary arrays. Quick Sort sorts with only O(log N) stack frames.
⢠Stability: Merge Sort preserves original order of equal items (Stable). Standard Quick Sort is Unstable.
⢠Linked Lists vs Arrays: Merge Sort is preferred for Linked Lists (no random access overhead). Quick Sort is preferred for Arrays (cache friendly).
1. What is the guaranteed worst-case time complexity of Merge Sort?
Explanation: Merge Sort guarantees O(N log N) across all input distributions.
2. What is the space complexity of standard Merge Sort on an array of N elements?
Explanation: Merge sort requires O(N) temporary space to merge sorted halves.
3. What element partitions the array into smaller and larger elements in Quick Sort?
Explanation: Quick Sort partitions elements around a selected Pivot.
4. Is Quick Sort an in-place sorting algorithm?
Explanation: Quick Sort partitions elements in-place.
Answer: A strategy that breaks a problem into smaller independent subproblems, solves them recursively, and combines results (e.g. Merge Sort).
Answer: Merge Sort is consistently O(N log N) in all cases.
Answer: O(N²) when the pivot chosen is consistently the smallest or largest element on sorted data. Can be prevented with randomized pivot.
Answer: Merge Sort requires O(N) auxiliary space for merging. Quick Sort sorts in-place with O(log N) stack space.
š Memoization (Top-Down DP)
Store results in a cache or dictionary. When a subproblem repeats, return cached result in O(1) instead of recalculating.
1. What two core properties must a problem have to be solved using Dynamic Programming?
Explanation: Overlapping Subproblems and Optimal Substructure are the two prerequisites for DP.
2. What is Top-Down Dynamic Programming commonly called?
Explanation: Top-down DP with caching is called Memoization.
3. What time complexity does DP achieve for calculating the N-th Fibonacci number?
Explanation: DP reduces Fibonacci from O(2^N) down to O(N) by solving each subproblem once.
4. What is Bottom-Up DP usually called?
Explanation: Bottom-up DP fills a table iteratively from base cases up.
Answer: DP is an optimization technique applied when a problem has: 1) Overlapping Subproblems, and 2) Optimal Substructure.
Answer: Memoization is recursive and caches results as functions return. Tabulation is iterative and fills an array from base cases up.
Answer: Naive recursion is O(2^N) exponential time. DP reduces it to O(N) linear time by eliminating duplicate calculations.
Answer: 0/1 Knapsack, Longest Common Subsequence (LCS), and Coin Change minimum coins.
š 1. The Backtracking Template: Generating Subsets & Combinations
Every backtracking problem follows a disciplined recursive pattern: 1. Base Case (valid solution found). 2. Iterate choices. 3. Make choice. 4. Recurse. 5. Undo choice (backtrack).
š 2. Classic Problem: Solving N-Queens with Pruning
Place N non-attacking queens on an NĆN chessboard. Backtracking prunes dead-end paths early by tracking occupied columns and positive/negative diagonals in O(1) time using hash sets.
1. What is the primary operational difference between Depth-First Search (DFS) and Backtracking?
Explanation: In backtracking, after recursively exploring a branch, you explicitly undo the choice (e.g. pop from the candidate list, unmark a cell) to restore state.
2. In the N-Queens problem, how can you test whether a diagonal (r, c) is already threatened in O(1) time?
Explanation: Across any positive diagonal, (row + col) is constant; across any negative diagonal, (row - col) is constant. Storing them in a set yields O(1) lookups.
3. What is the time complexity of generating all permutations of an array of N unique elements?
Explanation: There are N! permutations of an N-element set, resulting in O(N Ć N!) total operations.
4. What is 'Pruning' in a backtracking algorithm?
Explanation: Pruning cuts off branches of the state-space tree that cannot possibly yield valid solutions, drastically reducing runtime.
Answer: The standard 3-part template is:
def backtrack(state, candidate):
if is_solution(candidate):
output(candidate); return
for choice in get_choices(state):
if is_valid(choice):
make_choice(choice) # 1. CHOOSE
backtrack(state, candidate) # 2. EXPLORE
undo_choice(choice) # 3. UNCHOOSE (Backtrack)
Answer: Iterate over every empty cell ('.'). Try placing digits '1' through '9'. Check validity in row, column, and 3Ć3 sub-box. If valid, place the digit and recursively call solve(). If that recursion returns True, the puzzle is solved. If it returns False, backtrack by resetting the cell to '.' and try the next digit.
Answer:
1. Subsets: All $2^N$ sub-collections (order does not matter, any length).
2. Combinations: Selections of $K$ items from $N$ items where order does not matter (e.g. $[1, 2]$ is the same as $[2, 1]$).
3. Permutations: All $N!$ orderings of elements where order does matter (e.g. $[1, 2]$ is distinct from $[2, 1]$).
Answer: If intermediate state representations recur across different branches (e.g. Word Break, Partition Equal Subset Sum), pure backtracking becomes exponential $O(2^N)$. Storing visited states in a memoization cache (memo = {}) converts it into Top-Down Dynamic Programming, reducing complexity to polynomial time.
š 1. TrieNode Architecture & Insertion
Unlike binary search trees, no node in the Trie stores the whole key. Instead, its position in the tree defines its key. Each node contains a dictionary of children characters (or array of 26 letters) and a boolean 'is_end_of_word' flag.
š 2. Real-World Auto-Complete & Prefix Search (startsWith)
The true superpower of a Trie is prefix matching: finding all words starting with a given prefix in O(P + K) time, where P is prefix length and K is total matching characters.
1. What is the time complexity of searching for a word of length L in a Trie containing N total words?
Explanation: A Trie lookup checks characters one by one. Finding a word of length L takes exactly L steps, regardless of whether the Trie holds 10 or 100,000,000 words.
2. What is the primary trade-off of using a Trie compared to a Hash Table for string storage?
Explanation: Hash tables provide O(1) exact lookups but cannot do prefix search without scanning all keys. Tries excel at prefix matching at the cost of higher memory overhead.
3. What is the role of the 'is_end_of_word' boolean flag in a TrieNode?
Explanation: Without is_end_of_word, searching for 'app' in a Trie containing 'apple' would falsely indicate that 'app' was inserted as a complete word.
4. What compressed variation of a Trie merges consecutive single-child nodes to reduce memory footprint?
Explanation: A Radix Tree (or Patricia Trie) optimizes space by compacting chains of single-child nodes into single multi-character edges.
Answer: 1. Store words in a Trie where each node caches the Top-K most frequent searches passing through that prefix. 2. When a user types 'iph', navigate to the 'iph' node in $O(L)$ time and instantly read the pre-computed Top-K list in $O(1)$ time without traversing lower branches. 3. Periodically update frequencies using an offline MapReduce/Spark job.
Answer: Instead of searching for each dictionary word individually on the 2D grid ($O(W \times R \times C \times 4^L)$), insert all target words into a Trie. Then run a single DFS from each grid cell, traversing the grid and the Trie simultaneously. If a grid character is not in the current Trie node's children, prune the DFS branch immediately.
Answer: A Binary Trie stores numbers as sequences of 32 or 64 bits (children are 0 and 1). It is used to solve the Maximum XOR of Two Numbers in an Array in $O(N)$ time by greedily choosing opposite bits at each level, and in IP network routing (CIDR subnet matching).
Answer: Deletion uses post-order recursion: 1. Navigate to the word's terminal node and set is_end_of_word = False. 2. If the node has no other children, delete it. 3. Backtrack up the tree, deleting parent nodes as long as they have no other children and are not marked as end-of-word for other words.
š 1. DSU with Path Compression & Union by Rank
DSU supports two core operations: find(x) (finds the representative leader of x's set) and union(x, y) (merges the sets containing x and y). Path compression flattens the tree during find(), making subsequent lookups instant.
š 2. Kruskal's Minimum Spanning Tree (MST)
Kruskal's algorithm finds a subset of edges connecting all vertices with the minimum possible total weight with no cycles. It sorts edges by weight and uses DSU to greedily include edges that do not form cycles.
1. What is the amortized time complexity of DSU operations when both Path Compression and Union by Rank are used?
Explanation: Path Compression + Union by Rank guarantees nearly constant O(α(N)) amortized time, where α(N) never exceeds 4 for N up to the number of atoms in the universe.
2. How does DSU detect cycles when adding edges to an undirected graph?
Explanation: If two vertices already share the same representative set leader, a path already connects them; adding another edge between them creates a closed loop/cycle.
3. What is the first step in Kruskal's Minimum Spanning Tree algorithm?
Explanation: Kruskal's is a greedy algorithm: it sorts all edges by weight first, then iterates through them adding non-cyclical edges using DSU.
4. What optimization in DSU points every visited node directly to the root leader during find(x)?
Explanation: Path compression flattens the tree structure during traversal, so subsequent lookups on those nodes reach the root in a single jump.
Answer:
- Kruskal's: Edge-based algorithm. Sorts edges and uses DSU. Runs in $O(E \log E)$ time. Best for sparse graphs with fewer edges.
- Prim's: Vertex-based algorithm. Grows a tree from a start vertex using a Min-Heap. Runs in $O(E \log V)$ time with adjacency list. Best for dense graphs with many edges.
Answer: Initialize DSU with $N$ components (count = N). For each edge (u, v), attempt union(u, v). If union returns True (they were in different components), decrement count by 1. The final value of count is the number of connected components.
Answer: Flatten 2D grid coordinates $(r, c)$ into a 1D ID: $r \times \text{cols} + c$. When a new land cell is added, check its 4 orthogonal neighbors. For each neighbor that is already land, perform union(cell, neighbor) and decrement the island count.
Answer: Union by Rank attaches the tree of smaller depth under the root of the deeper tree, tracking upper-bound tree height. Union by Size tracks the count of nodes in each set and attaches the smaller set under the larger set. Both achieve the identical $O(\alpha(N))$ theoretical bounds.
š 1. Dijkstra's Algorithm with Min-Heap (heapq)
Dijkstra's greedy algorithm finds shortest paths from a source to all other vertices in non-negative weighted graphs. By prioritizing vertices with the minimum distance using Python's heapq, it relaxes adjacent edges efficiently.
š 2. Bellman-Ford Algorithm & Negative Cycle Detection
Dijkstra fails on graphs with negative edge weights. Bellman-Ford relaxes all edges V-1 times in O(V Ć E) time. A V-th relaxation check detects negative weight cycles (arbitrage opportunities in financial currency exchange).
1. Why does Dijkstra's algorithm fail on graphs with negative edge weights?
Explanation: Dijkstra assumes paths only grow in weight. A negative edge can make a previously visited vertex's path shorter, which Dijkstra will never revisit.
2. What is the time complexity of Dijkstra's algorithm implemented with a Min-Heap (heapq)?
Explanation: Each vertex is popped from the heap once (O(V log V)) and each edge relaxation pushes to the heap (O(E log V)), yielding O((V + E) log V).
3. How many times does the Bellman-Ford algorithm relax all edges to guarantee shortest paths?
Explanation: A simple shortest path in a graph with V vertices contains at most V - 1 edges. Therefore, V - 1 relaxation sweeps guarantee convergence.
4. Which algorithm finds all-pairs shortest paths between every pair of vertices in a directed graph?
Explanation: Floyd-Warshall is a dynamic programming algorithm that computes all-pairs shortest paths in O(V^3) time.
Answer: Pure Dijkstra on global road maps would explore millions of irrelevant nodes. Navigation engines use:
1. A* Search: Uses a geographic heuristic (Euclidean distance to destination) to steer search towards the target.
2. Bidirectional Search: Searches forward from source and backward from destination simultaneously, meeting in the middle (quadratically smaller search area).
3. Contraction Hierarchies: Precomputes highway shortcuts, bypassing local side streets.
Answer: Maintain a parent = {} map. Whenever an edge (u, v) successfully relaxes distances[v], record parent[v] = u. Once the target node is reached, backtrack from target to source using the parent map and reverse the resulting list.
Answer: Currency exchange is multiplicative: $C_1 \times R_{12} \times R_{23} > C_1$. Taking negative logarithms: $-\log(R_{12}) - \log(R_{23}) < 0$. By transforming exchange rates into negative log weights, an arbitrage opportunity becomes a Negative Weight Cycle, detectable by Bellman-Ford in polynomial time!
Answer: Relaxation tests whether going through vertex $u$ to vertex $v$ provides a shorter path than the currently recorded distance to $v$: if dist[u] + weight(u, v) < dist[v]: dist[v] = dist[u] + weight(u, v).
š 1. Essential Bit Tricks & Brian Kernighan's Algorithm
Learn instant O(1) bit tricks: checking if a bit is set (n & (1 << k)), toggling a bit (n ^ (1 << k)), clearing the lowest set bit (n & (n - 1)), and isolating the lowest set bit (n & -n).
š 2. Bitmasking: Representing Subsets as Integers
An integer's binary representation can represent a subset of elements. If the k-th bit is 1, the k-th element is present. A set of size N has 2^N subsets, mapped directly to integers from 0 to (1 << N) - 1.
1. What does the expression 'n & (n - 1)' do in binary arithmetic?
Explanation: Subtracting 1 flips all bits after the lowest set bit. Bitwise ANDing n with n - 1 clears that lowest set bit.
2. How many total subsets exist for a set containing N elements, and how is this written using bit shifts?
Explanation: Shifting 1 left by N positions (1 << N) evaluates to 2^N in O(1) CPU time.
3. How do you test if the k-th bit (0-indexed from right) of an integer n is set to 1?
Explanation: (n >> k) & 1 shifts the k-th bit to the least significant position and masks with 1.
4. What does 'n & -n' isolate in binary representation?
Explanation: In two's complement, -n = ~n + 1. Performing n & -n isolates the lowest set bit.
Answer: 1. XOR all numbers together; identical pairs cancel out, leaving xor_sum = a ^ b.
2. Find the lowest set bit in xor_sum using diff_bit = xor_sum & -xor_sum. (Since $a \neq b$, at least one bit must differ).
3. Divide the numbers into two groups based on whether that bit is 1 or 0, and XOR each group separately to isolate $a$ and $b$ in $O(N)$ time and $O(1)$ space.
Answer: When a DP problem requires tracking which subset of items has been visited (where $N \le 20$), storing the subset as a list or set is too slow. A bitmask integer (where bit $i$ is 1 if item $i$ is visited) represents the state in a single integer.
Classic example: The Traveling Salesperson Problem (TSP) solved in $O(N^2 \times 2^N)$ time with dp[mask][city].
Answer: Use the classic submask iteration trick:
submask = mask
while submask > 0:
# Process submask
submask = (submask - 1) & maskThis visits every valid submask without checking non-matching numbers, iterating all submasks across all masks in $O(3^N)$ instead of $O(4^N)$.
Answer: 1 << n is executed as a single-cycle native hardware bit-shift instruction in CPU registers, while pow(2, n) involves floating-point conversion and function call overhead.
š 1. Segment Tree Architecture: Build, Query & Update
A Segment Tree is a binary tree where each node stores an aggregate (sum, min, max) for a segment [L, R] of the array. The root covers [0, N-1], and leaves cover individual elements.
š 2. Fenwick Tree (Binary Indexed Tree - BIT)
A Fenwick Tree uses 1D array indexing based on powers of two (using x & -x) to achieve prefix sums and updates in O(log N) time with zero tree pointer overhead and minimal code.
1. What is the time complexity of a Range Query and Point Update in a Segment Tree?
Explanation: A Segment Tree balances range query and point update performance: both execute in logarithmic O(log N) time.
2. How much array memory is typically allocated for a Segment Tree covering an array of size N?
Explanation: Because a Segment Tree is a full binary tree whose height is ceil(log2 N) + 1, allocating 4 * N guarantees sufficient node slots.
3. What bitwise operation is used in a Fenwick Tree (BIT) to find the parent or next index?
Explanation: Fenwick trees advance through ranges by adding i & (-i) during updates and subtracting i & (-i) during prefix queries.
4. What technique allows a Segment Tree to perform RANGE UPDATES in O(log N) time rather than updating every leaf individually?
Explanation: Lazy Propagation defers updates to child nodes until the children are actually queried, achieving O(log N) range updates.
Answer:
- Fenwick Tree: Uses less memory ($O(N)$ vs $4N$), shorter code (10 lines), faster constant factor. Choose for Prefix/Range Sum queries with point updates.
- Segment Tree: Vastly more versatile. Can handle Range Minimum/Maximum (RMQ), Range GCD, complex custom aggregates, and Range Updates with Lazy Propagation (which Fenwick trees cannot easily do).
Answer: If you want to add $+5$ to all numbers in range $[100, 500]$, updating all 400 leaves individually takes $O(N)$ time. With Lazy Propagation, you update the high-level segment node covering $[100, 500]$ and store a lazy = 5 flag on it. Only when a future query traverses into its children do you 'push' the lazy value down one level, keeping range updates $O(\log N)$.
Answer: When the range coordinates are massive (e.g. $[0, 10^9]$), allocating a $4N$ array is impossible due to memory limits. A Dynamic Segment Tree creates nodes on-demand using pointers only when accessed during updates or queries, consuming $O(Q \log N)$ space for $Q$ queries.
Answer: Standard Fenwick trees rely on the mathematical property that subtraction can invert prefix operations (e.g. $\text{sum}(L, R) = \text{prefix}(R) - \text{prefix}(L-1)$). Because min() and max() have no inverse operation, Fenwick trees cannot generally support dynamic RMQ without complex two-tree workarounds. Use a Segment Tree or Sparse Table instead.